<template>
  <a-modal :visible="open" :width="860" :title="formTitle" @cancel="onClose">
    <a-form-model ref="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }" :model="form" :rules="rules">
      <div class="orders-title">订单信息</div>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="项目名称" prop="projectName">
            <a-input v-model="form.projectName" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="需求车型" prop="needVehicle">
            <a-input v-model="form.needVehicle" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="始发地" prop="beginAddr">
            <a-input v-model="form.beginAddr" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="公里数" prop="kilometre">
            <a-input v-model="form.kilometre" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }" label="目的地及联系人" prop="endContact">
            <a-textarea v-model="form.endContact" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <div class="orders-title">车辆信息</div>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="物流公司" prop="company">
            <a-input v-model="form.company" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="车型" prop="carType">
            <a-select :disabled="type === 2" v-model="form.carType" placeholder="请选择车型" :filterOption="filterOption"
              show-search>
              <a-select-option v-for="(d, index) in carTypeList" :key="index" :value="d.id.toString()">{{ d.info
                }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="车牌号" prop="carNum">
            <a-select :disabled="type === 2" v-model="form.carNum" placeholder="请选择车型" :filterOption="filterOption"
              show-search>
              <a-select-option v-for="(d, index) in carNumList" :key="index" :value="d.id.toString()">{{ d.carNo
                }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="证件照片" prop="carLicenseImgUrl">
            <base-upload v-model="form.carLicenseImgUrl" disabled></base-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
      <div class="orders-title">司机信息</div>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="司机" prop="carList">
            <a-select :disabled="type === 2" mode="multiple" v-model="form.carList" placeholder="请选择司机"
              :filterOption="filterOption" show-search>
              <a-select-option v-for="(d, index) in form.driverList" :key="index" :value="d.id.toString()">{{
                d.driverName
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12"><a-button type="primary" @click="handleAddDrive">新增司机</a-button></a-col>
      </a-row>
      <template v-for="item, index in selectCarList">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="司机姓名" prop="driverName">
              <a-input v-model="item.driverName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="联系电话" prop="driverPhone">
              <a-input v-model="item.driverPhone" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="身份证正面照" prop="driverIdCardBackImgUrl">
              <base-upload v-model="item.driverIdCardBackImgUrl" :limit="1" disabled></base-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="身份证反面照" prop="driverIdCardFrontImgUrl">
              <base-upload v-model="item.driverIdCardFrontImgUrl" :limit="1" disabled></base-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </template>
      <template v-for="item, index in addCarList">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="司机姓名" prop="driverName">
              <a-input v-model="item.driverName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="联系电话" prop="driverPhone">
              <a-input v-model="item.driverPhone" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="身份证正面照" prop="driverIdCardBackImgUrl">
              <base-upload v-model="item.driverIdCardBackImgUrl" :limit="1" disabled></base-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="身份证反面照" prop="driverIdCardFrontImgUrl">
              <base-upload v-model="item.driverIdCardFrontImgUrl" :limit="1" disabled></base-upload>
              <a style="position: absolute;right: 0; bottom: 10px;" @click="handleDelDrive(index)">删除该司机</a>
            </a-form-model-item>
          </a-col>
        </a-row>
      </template>
    </a-form-model>

    <template slot="footer">
      <a-space>
        <a-button v-if="type !== 2" type="primary" :loading="submitLoading" @click="submitForm">
          接单
        </a-button>
        <a-button type="dashed" @click="cancel">
          取消
        </a-button>
      </a-space>
    </template>
    <add-driver ref="addDriver" @ok="handleAddList"></add-driver>
  </a-modal>
</template>

<script>
import { getCarTypelist } from '@/api/vehicle/carinfo'
import { getCarType, getByCar, acceptOrder, getVehicleInfo, getChangeInfo, changeOrder } from '@/api/vehicle/orderinfo'
import baseUpload from '@/components/imgUpload/index.vue'
import addDriver from './CreateFormDriver'
import { detailsInsert, approvalFlow } from '@/api/demo'
export default {
  name: 'CreateForm',
  props: {
  },
  components: {
    baseUpload,
    addDriver
  },
  data() {
    return {
      submitLoading: false,
      formTitle: '接单',
      carTypeList: [], //车型字典
      carNumList: [], //车牌号字典
      id: null,
      vehicleId: null,
      processInstanceId: null,
      // 表单参数
      form: {
        id: null,
        projectName: null,
        beginAddr: null,
        endContact: undefined,
        needVehicle: null,
        kilometre: undefined,
        driverList: null,
        carType: undefined,
        carNum: undefined,
        carLicenseImgUrl: undefined,
        company: undefined,
        carList: undefined
      },
      open: false,
      rules: {
        carType: [
          { required: true, message: '车型不能为空', trigger: 'blur' }
        ],

        carNum: [
          { required: true, message: '车牌号不能为空', trigger: 'change' }
        ],

      },
      type: null,
      first: false,
      firstCarNum: false,
      selectCarList: [],
      addCarList: [],
    }
  },
  filters: {
  },
  created() {
    this.getOptionDic()
  },
  computed: {
  },
  watch: {
    'form.carType': function (val, oldVal) {
      getCarType({ carType: val }).then((res) => {
        this.carNumList = res.data
        if (this.first && oldVal !== undefined) {
          this.form.driverList = []
          this.form.carNum = undefined
        } else {
          this.first = true
        }

      })
    },
    'form.carNum': function (val, oldVal) {
      if (this.carNumList.length === 0) {
        getCarType({ carType: this.form.carType }).then((res) => {
          this.carNumList = res.data
          this.form.carLicenseImgUrl = this.carNumList?.find(item => item.id == val)?.carLicenseImgUrl
        })
      } else {
        this.form.carLicenseImgUrl = this.carNumList?.find(item => item.id == val)?.carLicenseImgUrl
      }
      // 
      this.form.driverList = []
      getByCar({ id: val }).then((res) => {
        this.form.driverList = res.data
        // 如果修改或详情页 一开始拿到司机id列表  selectCarList是空的，所以再次赋值
        if (!this.firstCarNum && (this.type == 1 || this.type == 2)) {
          this.form.carList = this.form.carList ? [...this.form.carList] : []
        } else {
          this.firstCarNum = true
          this.form.carList = []
        }
      })
    },
    'form.carList':
      function (val) {
        this.selectCarList = this.form.driverList?.filter(item => val.includes(item.id.toString()))
      },
  },
  mounted() {
  },
  methods: {
    handleDelDrive(data) {
      this.addCarList = this.addCarList?.filter((item, index) => index !== data)
    },
    handleAddDrive() {
      this.$refs.addDriver.handleAdd()
    },
    handleAddList(val) {
      this.addCarList.push(val)
    },
    onClose() {
      this.open = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 获取字典 */
    getOptionDic() {
      //获取车型字典
      getCarTypelist().then(res => {
        this.carTypeList = res.data
      })
    },
    // 筛选功能
    filterOption(inputValue, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        beginAddr: null,
        endContact: undefined,
        needVehicle: null,
        kilometre: null,
        driverList: null,
        carType: undefined,
        carNum: undefined,
        carLicenseImgUrl: undefined,
        company: undefined,
        carList: undefined
      }
      this.first = false
      this.firstCarNum = false
      this.addCarList = []
      this.$refs.form.resetFields()
    },
    /** 接单按钮操作 */
    handleAdd(row, type) {
      // 0 新增 1修改  2详情
      this.id = row.id
      this.vehicleId = row.vehicleId
      this.processInstanceId = row.processInstanceId
      this.open = true
      this.type = type
      getVehicleInfo({ id: this.vehicleId }).then((res) => {
        for (let item in this.form) {
          this.form[item] = res.data[item]
        }
        this.form.company = row.deptName
      })
      this.handleGetContent()
    },
    handleGetContent() {
      if (this.type == 1 || this.type == 2) {
        getChangeInfo({ id: this.id }).then((res) => {
          this.form.carType = res.data.carType
          this.form.carNum = res.data.carId.toString()
          this.form.carList = res.data.driverIdList.map(item => item.id.toString())
          this.addCarList = res.data.appendDriverList
        })
      } else {
        this.first = true
        this.firstCarNum = true
      }
    },
    async handleOrder() {
      const data = { id: this.id, carId: this.form.carNum, driverIdList: this.form.carList, appendDriverList: this.addCarList }
      let res
      if (this.type === 0) {
        res = await acceptOrder(data)
      } else {
        res = await changeOrder(data)
      }
      if (res.code === 200) {
        this.submitLoading = true
        let driver = this.selectCarList.map(item => `司机：${item.driverName}  联系电话：${item.driverPhone}`).join('\n');
        const parms = {
          comments: `物流公司：${this.form.company ?? ''}\n车辆信息：${this.form.carType ?? ''}\n${driver}`,
          infoId: this.vehicleId,
          imgLinks: this.form.carLicenseImgUrl,
          type: 0
        }
        detailsInsert(parms).then(response => {
          approvalFlow({ result: 'agree', processInstanceId: this.processInstanceId }).then(() => {
            this.$message.success(
              this.type === 0 ? '接单成功' : '变更成功',
              3
            )
            this.submitLoading = false
            this.cancel()
            this.$emit('ok')
          }).catch((res) => {
            this.$message.error(
              '审批失败',
              3
            )
          })
        }).catch((res) => {
          this.$message.error(
            '评论失败',
            3
          )
        })
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.handleOrder()
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.orders-title {
  margin-bottom: 10px;
  font-size: 16px;
  color: black;
  font-weight: 600;
  padding-left: 10px;
  border-left: 3px solid #1890ff;
}
</style>
